<template>
  <div>
    <!-- 表单 -->
    <FormPanel ref="form" labelWidth="100" :cols="3" :list="formList" :isSubmitBtn="false" @formChange="formChange"></FormPanel>
    <!-- 表格 -->
    <FilterTable
      ref="table"
      height="auto"
      :columns="columns"
      columnsRef="partPartOutboundRepairMaterialsComponentsEditPanel"
      :dataSource="dataSource"
      :onColumnsChange="columns => (this.columns = columns)"
    ></FilterTable>
    <el-row class="btn-wrap">
      <el-button
        type="primary"
        @click="
          () => {
            this.$refs.form.SUBMIT_FORM();
          }
        "
        >确 定</el-button
      >
      <el-button @click="$emit('cancel')">取 消</el-button>
    </el-row>
  </div>
</template>

<script>
import { state, mutations } from './../store';
import { dictionary } from '@/utils/dictMixin';
import { isAuthorized } from '@/utils/index';
import { queryPartStock } from '@/api/part/partOutbound/repairMaterials/index.js';
import { getStorageList } from '@/api/part/partOutbound/repairMaterials/dict';
import Cookies from 'js-cookie';
import { getWxlxSelect, getSfqfSelect } from '@/api/repair/repairReception/customer';

const jglx_dict = [
  { text: '终端建议零售VIP价格', value: 82481001, filedName: 'INSTRUCT_PRICE' },
  { text: '常规订货价', value: 82481002, filedName: 'PLAN_PRICE' },
  { text: '含税成本价', value: 82481003, filedName: 'COST_PRICE' },
  { text: '终端建议零售价格', value: 82481004, filedName: 'INSURANCE_PRICE' },
  { text: '索赔价', value: 82481005, filedName: 'CLAIM_PRICE' },
  { text: '最新进货价', value: 82481006, filedName: 'LATEST_PRICE' }
];

export default {
  name: 'wxll_edit',
  mixins: [dictionary],
  props: ['selectRow', 'repairTypeCode'],
  data() {
    return {
      formList: this.createList(),
      columns: this.createColumns(),
      dataSource: [],
      InitSalePrace: 0, // 初始销售价格
      partInfoRow: {}
    };
  },
  mounted() {
    window.cgrk_edit = this;
    console.log('wxll_edit mounted', this.selectRow);
    this.dataSource = [this.selectRow];
    this.InitSalePrace = this.selectRow.PART_SALES_PRICE || 0;
    this.partInfoRow = Object.assign({}, this.selectRow);
    this.getSfqfSelect();
    this.queryPartStock(this.partInfoRow);
    this.getStorage();
  },
  methods: {
    async getSfqfSelect() {
      let res = await getSfqfSelect();
      if (res.resultCode == 200) {
        this.formList.find(x => x.fieldName === 'CHARGE_PARTITION_CODE').itemList = res.data.map(x => {
          return { text: x.CHARGE_PARTITION_NAME, value: x.CHARGE_PARTITION_CODE };
        });
      }
    },
    createList() {
      return [
        {
          type: 'SELECT',
          label: '仓库名称',
          fieldName: 'STORAGE_CODE',
          initialValue: '',
          placeholder: '',
          itemList: [],
          disabled: true
        },
        {
          type: 'INPUT',
          label: '配件代码',
          fieldName: 'PART_NO',
          initialValue: '',
          placeholder: '',
          disabled: true
        },
        {
          type: 'INPUT',
          label: '配件名称',
          fieldName: 'PART_NAME',
          initialValue: '',
          placeholder: '',
          disabled: true
        },
        {
          type: 'SELECT',
          label: '领料人',
          fieldName: 'RECEIVER',
          initialValue: '',
          filterable: true,
          // disabled: true,
          itemList: []
          // rules: [{ type: 'number', required: true, message: '这是必填字段', trigger: ['blur', 'change'] }]
        },
        {
          type: 'SELECT',
          label: '维修项目',
          fieldName: 'LABOUR_CODE',
          disabled: true,
          initialValue: '',
          placeholder: '',
          // disabled: true,
          itemList: []
          // rules: [{ type: 'string', required: true, message: '这是必填字段', trigger: ['blur', 'change'] }]
        },
        {
          type: 'SELECT',
          label: '价格类型',
          fieldName: 'PRICE_TYPE',
          disabled: true,
          placeholder: '',
          itemList: this.createDictList('8248'),
          // rules: [{ type: 'number', required: true, message: '这是必填字段', trigger: ['blur', 'change'] }],
          change: val => {
            this.price_type_change(val);
          }
        },
        {
          type: 'INPUT_NUMBER',
          label: '价格系数',
          fieldName: 'PRICE_RATE',
          disabled: true,
          precision: 2,
          // rules: [{ required: true, message: '请输入价格系数', trigger: 'blur' }],
          max: 9.99,
          initialValue: '',
          placeholder: '',
          change: val => {
            this.price_rate_change(val);
          }
        },
        {
          type: 'INPUT_NUMBER',
          label: '配件销售单价',
          fieldName: 'PART_SALES_PRICE',
          precision: 2,
          disabled: true,
          initialValue: '',
          placeholder: '',
          // rules: [{ required: true, message: '这是必填字段', trigger: ['blur', 'change'] }],
          change: val => {
            // this.part_sales_price_change(val);
          }
        },
        {
          type: 'INPUT_NUMBER',
          label: '配件数量',
          fieldName: 'PART_QUANTITY',
          precision: 2,
          initialValue: 1,
          min: 0,
          // disabled: true,
          rules: [{ required: true, message: '这是必填字段', trigger: 'blur' }],
          change: val => {
            this.part_quantity_change(val);
          }
        },
        {
          type: 'INPUT',
          label: '配件销售金额',
          fieldName: 'PART_SALES_AMOUNT',
          precision: 2,
          initialValue: '',
          placeholder: '',
          disabled: true
        },
        {
          type: 'SELECT',
          label: '收费区分',
          fieldName: 'CHARGE_PARTITION_CODE',
          disabled: true,
          initialValue: '',
          itemList: [],
          // itemList: this.createDictList('8102'),
          change: val => {
            this.charge_partition_code_change(val);
          }
        },
        {
          type: 'SELECT',
          label: '主要配件',
          fieldName: 'IS_MAIN_PART',
          initialValue: 10041002,
          itemList: this.createDictList('1004')
        }
      ];
    },
    createColumns() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          width: 70,
          sorter: true,
          render: props => {
            return <span>{props.$index + 1}</span>;
          }
        },
        {
          title: '终端建议零售VIP价格',
          sorter: true,
          dataIndex: 'INSTRUCT_PRICE',
          precision: 2,
          filter: true,
          filterType: 'number'
        },
        {
          title: '常规订货价',
          sorter: true,
          dataIndex: 'PLAN_PRICE',
          precision: 2,
          filter: true,
          filterType: 'number'
        },
        {
          title: '含税成本价',
          sorter: true,
          dataIndex: 'COST_PRICE',
          precision: 2,
          filter: true,
          filterType: 'number'
        },

        {
          title: '索赔价',
          sorter: true,
          dataIndex: 'CLAIM_PRICE',
          precision: 2,
          filter: true,
          filterType: 'number'
        },
        {
          title: '终端建议零售价格',
          sorter: true,
          dataIndex: 'INSURANCE_PRICE',
          precision: 2,
          filter: true,
          filterType: 'number'
        },
        {
          title: '最新进货价',
          sorter: true,
          dataIndex: 'LATEST_PRICE',
          precision: 2,
          filter: true,
          filterType: 'number'
        },

        {
          title: '账面库存',
          sorter: true,
          dataIndex: 'STOCK_QUANTITY',
          precision: 2,
          filter: true,
          filterType: 'number'
        },
        {
          title: '可用库存',
          sorter: true,
          dataIndex: 'USEABLE_STOCK',
          precision: 2,
          filter: true,
          filterType: 'number'
        },

        {
          title: '锁定量',
          sorter: true,
          dataIndex: 'LOCKED_QUANTITY',
          precision: 2,
          filter: true,
          filterType: 'number'
        },
        {
          title: '替代配件',
          sorter: true,
          dataIndex: 'OPTION_NO',
          filter: true,
          filterType: 'input'
        },
        {
          title: '替代件库存',
          sorter: true,
          dataIndex: 'OPTION_STOCK',
          precision: 2,
          filter: true,
          filterType: 'number'
        },
        {
          title: '配件类别',
          sorter: true,
          dataIndex: 'PART_GROUP_CODE',
          editable: false,
          editType: 'select',
          editItems: this.createDictList(8247),
          filter: true,
          filterType: 'checkbox',
          filterItems: this.createDictList(8247)
        },
        {
          title: '单位',
          sorter: true,
          dataIndex: 'UNIT_NAME',
          filter: true,
          filterType: 'input'
        }
      ];
    },

    formChange(val) {
      console.log('formChange', val);
      const row = Object.assign({}, this.dataSource[0], this.partInfoRow, val, { $index_edit: this.partInfoRow.$index_edit });
      // 判断 配件是否已选
      if (!val['PART_NO']) {
        return this.$notify.warning({ title: '警告', message: '未选择配件' });
      }
      // 出库数量不能为0
      if (!row.PART_QUANTITY) {
        return this.$notify.warning({ title: '警告', message: '出库数量不能为0' });
      }

      // 给父表加的数据
      this.$emit('confirm', row);
    },

    // 查询配件信息  通过双击配件搜索列表传来的参数
    async queryPartStock(row) {
      const res = await queryPartStock({
        partNo: row['PART_NO'],
        storageCode: row['STORAGE_CODE']
      });
      if (res.resultCode != 200) {
        console.log('查询配件 失败', res);
        return;
      }
      console.log('查询配件 成功', res);

      const part = res.data.rows[0];
      if (res.data.rows.length) {
        this.dataSource = res.data.rows;
      }
      // 整合配件信息
      const partInfo = Object.assign({}, part, row);
      console.log('整合后的配件信息', partInfo);
      const partInfoRow = this.partInfoRow;
      this.formList.forEach(element => {
        if (element.fieldName === 'RECEIVER') {
          element.initialValue = String(partInfoRow[element.fieldName]);
        } else {
          element.initialValue = partInfoRow[element.fieldName];
        }
      });
      this.initDictData();
    },
    /** 字典 S */
    async initDictData() {
      // 仓库
      this.formList.find(x => x.fieldName === 'STORAGE_CODE').itemList = state.dict_ck;
      // 领料人
      // const llr = await getLingLiaoRenSelect();
      this.formList.find(x => x.fieldName === 'RECEIVER').itemList = state.dict_allUser;
      // console.log(this.formList.find(x => x.fieldName === 'RECEIVER').itemList);
      // console.log(typeof this.formList.find(x => x.fieldName === 'RECEIVER').initialValue);
      // 维修项目
      this.formList.find(x => x.fieldName === 'LABOUR_CODE').itemList = state.dict_xlxm;
    },
    /** 价格计算逻辑 S */
    // 价格类型 变化  计算 配件销售单价 配件销售金额
    price_type_change(price_type) {
      this.calculateLogic(price_type);
    },
    // 价格系数变化 计算 配件销售单价(价格类型*价格系数)  配件销售金额(配件销售单价*配件数量)
    price_rate_change(price_rate) {
      const priceType = this.formList.find(x => x.fieldName === 'PRICE_TYPE').initialValue;
      this.calculateLogic(priceType, price_rate);
    },
    // // 配件销售单价变化 计算价格系数(销售单价 / 价格类型) 和 销售金额
    // part_sales_price_change(part_sales_price) {
    //   var val = part_sales_price || 0;
    //   let scalePrice = Number(this.InitSalePrace).toFixed(2);
    //   if (scalePrice > Number(val).toFixed(2)) {
    //     val = scalePrice;
    //   }
    //   console.log('配件销售单价 PART_SALES_PRICE change', val);
    //   // 计算价格系数(销售单价 / 价格类型) 和 销售金额
    //   const PART_SALES_PRICE = val;
    //   // 获取基础价格计算价格系数
    //   const priceType = this.formList.find(x => x.fieldName === 'PRICE_TYPE').initialValue;
    //   const filedName = jglx_dict.find(x => x.value == priceType).filedName;
    //   const PRICE_TYPE = this.dataSource[0][filedName] || 1; // 默认是1
    //   // const PRICE_RATE = Number(val) / PRICE_TYPE;
    //   // this.formList.find(x => x.fieldName === 'PRICE_RATE').initialValue = PRICE_RATE;
    //   const PART_QUANTITY = this.formList.find(x => x.fieldName === 'PART_QUANTITY').initialValue;
    //   const PART_SALES_AMOUNT = Number(PART_SALES_PRICE) * Number(PART_QUANTITY);
    //   this.formList.find(x => x.fieldName === 'PART_SALES_AMOUNT').initialValue = PART_SALES_AMOUNT.toFixed(2);
    //   this.$nextTick(() => {
    //     if (!part_sales_price) {
    //       this.formList.find(x => x.fieldName === 'PART_SALES_PRICE').initialValue = '0.00';
    //       // this.formList = [...this.formList];
    //     }
    //   });
    // },
    part_quantity_change(part_quantity) {
      var val = part_quantity || 0;
      console.log('配件数量 PART_QUANTITY change', val);
      // 计算配件销售金额 (配件销售单价*配件数量)
      const priceType = this.formList.find(x => x.fieldName === 'PRICE_TYPE').initialValue;
      this.$nextTick(x => {
        this.calculateLogic(priceType);
      });
      // const PART_SALES_PRICE = this.formList.find(x => x.fieldName === 'PART_SALES_PRICE').initialValue;
      // const PART_SALES_AMOUNT = Number(PART_SALES_PRICE) * Number(val);
      // this.formList.find(x => x.fieldName === 'PART_SALES_AMOUNT').initialValue = PART_SALES_AMOUNT.toFixed(2);
      // this.$nextTick(() => {
      //   if (!part_quantity) {
      //     this.formList.find(x => x.fieldName === 'PART_QUANTITY').initialValue = '0.00';
      //   }
      // });
    },
    // 收费区分变化
    charge_partition_code_change(charge_partition_code) {
      console.log('收费区分 change', charge_partition_code);
      // a)选择免费时，价格类型自动选择索赔 82481005
      // b)选择自费时，价格类型自动选择终端建议零售VIP价格 82481001
      // c)选择保险时，价格类型自动选择终端建议零售价格 82481004
      // d)选择经销商时，价格类型自动选择成本价 82481003
      // 索赔 - 索赔 82481005

      // 82481001-终端建议零售VIP价格
      // 82481002-常规订货价
      // 82481003-含税成本价
      // 82481004-终端建议零售价格
      // 82481005-索赔价
      // 82481006-最新进货价
      if (charge_partition_code == 81021001) {
        // 免费 - 价格类型索赔
        this.formList.find(x => x.fieldName === 'PRICE_TYPE').initialValue = 82481005;
      }
      if (charge_partition_code == 81021002) {
        // 自费
        this.formList.find(x => x.fieldName === 'PRICE_TYPE').initialValue = 82481001;
      }
      if (charge_partition_code == 81021003) {
        // 保险
        this.formList.find(x => x.fieldName === 'PRICE_TYPE').initialValue = 82481004;
      }
      if (charge_partition_code == 81021004) {
        // 经销商
        this.formList.find(x => x.fieldName === 'PRICE_TYPE').initialValue = 82481003;
      }
      if (charge_partition_code == 81021005) {
        // 索赔
        this.formList.find(x => x.fieldName === 'PRICE_TYPE').initialValue = 82481005;
      }
      let priceType = this.formList.find(x => x.fieldName === 'PRICE_TYPE').initialValue;
      this.calculateLogic(priceType);
    },

    calculateLogic(price_type, price_rate, part_sales_price, charge_partition_code) {
      // 设置PRICE_TYPE
      this.formList.find(x => x.fieldName === 'PRICE_TYPE').initialValue = price_type;
      const filedName = jglx_dict.find(x => x.value == price_type).filedName;
      const PRICE_TYPE = this.dataSource[0][filedName] || 1; // 默认是1
      const PRICE_RATE = price_rate ? price_rate : this.formList.find(x => x.fieldName === 'PRICE_RATE').initialValue; // 默认也是1
      const PART_SALES_PRICE = Number(PRICE_TYPE) * Number(PRICE_RATE);
      // 设置单价
      this.formList.find(x => x.fieldName === 'PART_SALES_PRICE').initialValue = PART_SALES_PRICE.toFixed(2);

      const PART_QUANTITY = this.formList.find(x => x.fieldName === 'PART_QUANTITY').initialValue;
      if (PART_QUANTITY) {
        const PART_SALES_AMOUNT = Number(PART_SALES_PRICE) * Number(PART_QUANTITY);
        // 设置总价
        this.formList.find(x => x.fieldName === 'PART_SALES_AMOUNT').initialValue = PART_SALES_AMOUNT.toFixed(2);
      }
    },
    /** 价格计算逻辑 E */

    async getStorage() {
      const res = await getStorageList();
      this.formList.find(x => x.fieldName == 'STORAGE_CODE').itemList = res.data.map(x => ({ value: x.STORAGE_CODE, text: x.STORAGE_NAME }));
    }
  }
};
</script>

<style scoped>
.btn-wrap {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 60px;
}
</style>
